import { useEffect, useRef, useState } from 'react';
import { DragStyle } from './style';
import { Flip } from './Flip';

const ListSort = () => {
	const [list] = useState(new Array(5).fill(0));

	const boxRef = useRef<HTMLDivElement>();
	const sourceNode = useRef<HTMLDivElement>();
	const flip = useRef<Flip>();

	function foo() {
		boxRef.current.ondragstart = (e) => {
			setTimeout(() => {
				(e.target as HTMLDivElement).classList.add('moving');
			}, 0);
			sourceNode.current = e.target as HTMLDivElement;
			e.dataTransfer.effectAllowed = 'move';
			flip.current = new Flip(boxRef.current.children, 0.5);
		};

		boxRef.current.ondragover = (e) => e.preventDefault();

		boxRef.current.ondragenter = (e) => {
			e.preventDefault();
			if (e.target === boxRef.current || e.target === sourceNode.current) return;
			const children = Array.from(boxRef.current.children);
			const sourceIndex = children.indexOf(sourceNode.current as Element);
			const targetIndex = children.indexOf(e.target as Element);
			if (sourceIndex < targetIndex) {
				boxRef.current.insertBefore(sourceNode.current, (e.target as Element).nextElementSibling);
			} else {
				boxRef.current.insertBefore(sourceNode.current, e.target as Element);
			}
			flip.current.play();
		};

		boxRef.current.ondragend = (e) => {
			(e.target as HTMLDivElement).classList.remove('moving');
		};
	}

	useEffect(() => {
		foo();
	}, []);

	return (
		<DragStyle>
			<div ref={boxRef} className="drag-box">
				{list.map((_, index) => (
					<div key={index} className="item" draggable>
						{index + 1}
					</div>
				))}
			</div>
		</DragStyle>
	);
};

export default ListSort;
